package com.itheima.feign.config;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
@Slf4j
public class FeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                // 获取主线程中的用户信息（例如 Token）
                String token = request.getHeader("Authorization");
                if (token != null) {
                    // 将 Token 添加到 Feign 请求头中
                    log.info("interface中的token:{}", token);
                    requestTemplate.header("Authorization", token);
                }
            }
        };
    }
}

